<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use App\Models\Member;
use App\Models\Address;

class Store extends Model
{
    protected $table = 'ims_yz_store';
    
    protected $fillable = [
        'uniacid', 'uid', 'store_name', 'thumb', 'category_id', 'province_id', 'city_id', 
        'district_id', 'street_id', 'address', 'longitude', 'latitude', 'mobile', 
        'store_introduce', 'username', 'password', 'template_id', 'salers', 'cashier_id',
        'business_hours_start', 'business_hours_end', 'aptitude_imgs', 'dispatch_type',
        'affiche', 'user_uid', 'information', 'is_black', 'banner_thumb', 'is_hide',
        'specify_show', 'operating_state', 'boss_uid', 'audio_open', 'initials',
        'validity', 'validity_status', 'id_card_imgs', 'other_imgs', 'yun_horn',
        'zkc_pay', 'salt', 'home_store_url', 'goods_store_url', 'collect_money_url',
        'payment_jump_minapp', 'payment_jump_h5', 'is_open_jump', 'separate_payment_jump_minapp',
        'separate_payment_jump_h5', 'balance_id', 'platform_ids', 'settlement_num',
        'settlement_type', 'recruiter_id', 'platform_id', 'is_recommend'
    ];

    protected $casts = [
        'created_at' => 'integer',
        'updated_at' => 'integer',
        'deleted_at' => 'integer',
         'aptitude_imgs' => 'json',
        'id_card_imgs'  => 'json',
        'other_imgs'    => 'json',
        'dispatch_type' => 'json'
    ];

    public $timestamps = true;

    /**
     * 获取日期格式
     */
    public function getDateFormat()
    {
        return 'U';
    }

    /**
     * 获取创建时间属性
     */
    public function getCreatedAtAttribute($value)
    {
        return $value ? Carbon::createFromTimestamp($value) : null;
    }

    /**
     * 获取更新时间属性
     */
    public function getUpdatedAtAttribute($value)
    {
        return $value ? Carbon::createFromTimestamp($value) : null;
    }

    /**
     * 获取删除时间属性
     */
    public function getDeletedAtAttribute($value)
    {
        return $value ? Carbon::createFromTimestamp($value) : null;
    }

    /**
     * 获取完整地址
     */
    public function getFullAddressAttribute2()
    {
        $address = '';
        
        // 获取省市区名称
        if ($this->province_id) {
            $province = Address::find($this->province_id);
            if ($province) $address .= $province->areaname;
        }
        
        if ($this->city_id) {
            $city = Address::find($this->city_id);
            if ($city) $address .= $city->areaname;
        }
        
        if ($this->district_id) {
            $district = Address::find($this->district_id);
            if ($district) $address .= $district->areaname;
        }
        
        if ($this->address) {
            $address .= $this->address;
        }
        
        return $address;
    }

    /**
     * 获取分类名称
     */
    public function getCategoryNameAttribute()
    {
        // 优先使用已加载的关联
        if ($this->relationLoaded('category')) {
            return $this->category ? ($this->category->name ?? $this->category->title ?? $this->category->category_name ?? '未分类') : '未分类';
        }

        // 兜底从表中查询（兼容字段 name/title/category_name）
        $row = \DB::table('ims_yz_store_category')->where('id', $this->category_id)->first();
        if ($row) {
            return $row->name ?? $row->title ?? $row->category_name ?? '未分类';
        }
        return '未分类';
    }

    /**
     * 获取有效期文本
     */
    public function getValidityTextAttribute()
    {
        if (!$this->validity || $this->validity == 0) {
            return '无限期';
        }
        
        return Carbon::createFromTimestamp($this->validity)->format('Y-m-d');
    }

    /**
     * 关联用户表
     */
    public function owner()
    {
        return $this->belongsTo(Member::class, 'uid', 'uid');
    }

    /**
     * 关联地址表 - 省份
     */
    public function province()
    {
        return $this->belongsTo(Address::class, 'province_id', 'id');
    }

    /**
     * 关联地址表 - 城市
     */
    public function city()
    {
        return $this->belongsTo(Address::class, 'city_id', 'id');
    }

    /**
     * 关联地址表 - 区县
     */
    public function district()
    {
        return $this->belongsTo(Address::class, 'district_id', 'id');
    }

    // 访问器方法
    public function getBlackObjAttribute()
    {
        $obj = [];
        if ($this->is_black == 0) {
            $obj = [
                'style' => 'fa fa-minus-circle',
                'name'  => '设置黑名单'
            ];
        }
        if ($this->is_black == 1) {
            $obj = [
                'style' => 'fa fa-plus-circle',
                'name'  => '加入白名单'
            ];
        }
        return $obj;
    }

    public function getHideObjAttribute()
    {
        $obj = [];
        if ($this->is_hide == 0) {
            $obj = [
                'style' => 'fa fa-circle',
                'name'  => '设置不显示'
            ];
        }
        if ($this->is_hide == 1) {
            $obj = [
                'style' => 'fa fa-circle-o',
                'name'  => '设置显示'
            ];
        }
        return $obj;
    }

    public function getDispatchAttribute()
    {
        $dispatch = '';
        if (is_array($this->dispatch_type)) {
            foreach ($this->dispatch_type as $value) {
                if ($value == 1) {
                    $dispatch .= '快递、';
                }
                if ($value == 2) {
                    $dispatch .= '上门自提、';
                }
                if ($value == 3) {
                    $dispatch .= '门店配送、';
                }
            }
        }
        return rtrim($dispatch, '、');
    }

    public function getValidityStatusNameAttribute()
    {
        $name = '入驻中';
        if ($this->validity_status == 1) {
            $name = '已过期';
        }
        return $name;
    }

    public function getAverageScoreAttribute()
    {
        // 默认五星好评
        return 5;
    }

    public function getOrderTotalAttribute()
    {
        return StoreOrder::where('store_id', $this->id)->count();
    }

    public function getFullAddressAttribute()
    {
        $address = '';
        if ($this->province) {
            $address .= $this->province->name;
        }
        if ($this->city) {
            $address .= $this->city->name;
        }
        if ($this->district) {
            $address .= $this->district->name;
        }
        $address .= $this->address;
        return $address;
    }

    public function getDispatchTextAttribute()
    {
        $dispatch_text = [];
        if (is_array($this->dispatch_type)) {
            foreach ($this->dispatch_type as $value) {
                if ($value == 1) {
                    $dispatch_text[] = '快递';
                }
                if ($value == 2) {
                    $dispatch_text[] = '上门自提';
                }
                if ($value == 3) {
                    $dispatch_text[] = '门店配送';
                }
            }
        }
        return $dispatch_text;
    }
    
    /**
     * 关联会员信息
     */
    public function member()
    {
        return $this->belongsTo(Member::class, 'uid', 'uid');
    }
    
    /**
     * 门店的自提点申请记录
     */
    public function pickupPointApplications()
    {
        return $this->hasMany(PickupPointApplication::class, 'store_id');
    }
    
    /**
     * 门店的最新自提点申请
     */
    public function latestPickupPointApplication()
    {
        return $this->hasOne(PickupPointApplication::class, 'store_id')->latest();
    }
    
    /**
     * 门店已通过的自提点申请
     */
    public function approvedPickupPointApplications()
    {
        return $this->hasMany(PickupPointApplication::class, 'store_id')->where('status', 'approved');
    }
    
    /**
     * 自提点供应商关联记录
     */
    public function pickupPointVendors()
    {
        return $this->hasMany(PickupPointVendor::class, 'store_id');
    }
    
    /**
     * 通过中间表关联的供应商（多对多）
     */
    public function vendors()
    {
        return $this->belongsToMany(
            Vendor::class,
            'ims_yz_pickup_point_vendors',
            'store_id',
            'vendor_id'
        )->withTimestamps()->withTrashed();
    }
    
    /**
     * 获取门店的所有供应商
     */
    public function getVendors()
    {
        return $this->vendors()->get();
    }
    
    /**
     * 检查门店是否关联了指定供应商
     */
    public function hasVendor($vendorId)
    {
        return $this->vendors()->where('vendor_id', $vendorId)->exists();
    }
    
    /**
     * 所属平台
     */
    public function platform()
    {
        return $this->belongsTo(StorePlatform::class, 'platform_id');
    }
    
    // 静态方法
    public static function getList($search)
    {
        return self::search($search);
    }

    public static function getStoreById($id)
    {
        return self::where('id', $id)->first();
    }

    public static function getStoreByUid($uid)
    {
        return self::where('uid', $uid)->first();
    }

    public static function getStoreByCashierId($cashier_id)
    {
        return self::where('cashier_id', $cashier_id)->first();
    }

    public static function getStoreByCategoryId($category_id)
    {
        return self::where('category_id', $category_id)->get();
    }

    public static function getStoreByUserUid($user_uid)
    {
        if (Schema::hasColumn('yz_store', 'user_uid')) {
            return self::where('user_uid', $user_uid)->get();
        }
        return collect([]);
    }

    public static function getCommentData($store_id)
    {
        // 评论数据获取逻辑
        return [];
    }

    public static function getCommentDataBatch($store_ids)
    {
        // 批量评论数据获取逻辑
        return [];
    }

    public static function getGoodsTotal($store_id)
    {
        // 商品总数获取逻辑
        return 0;
    }

    public static function getOrderCount($store_id)
    {
        // 订单数量获取逻辑
        return 0;
    }

    public static function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        // 距离计算逻辑
        return 0;
    }

    public static function getFirstCharter($str)
    {
        // 首字母获取逻辑
        return '';
    }

    // 作用域方法
    public function scopeIsHide($query)
    {
        return $query->where('is_hide', 0);
    }

    public function scopeByCategoryId($query, $category_id)
    {
        return $query->where('category_id', $category_id);
    }

    public function scopeByCashierId($query, $cashier_id)
    {
        return $query->where('cashier_id', $cashier_id);
    }

    public function scopeById($query, $id)
    {
        return $query->where('id', $id);
    }

    public function scopeByUid($query, $uid)
    {
        return $query->where('uid', $uid);
    }

    public function scopeByUserUid($query, $user_uid)
    {
        return $query->where('user_uid', $user_uid);
    }

    public function scopeValidity($query)
    {
        return $query->where('validity_status', '!=', 1);
    }

    public function scopeSearch($query, $params)
    {
        if (!$params) {
            return $query;
        }
        if (isset($params['store_id']) && $params['store_id']) {
            $query->where('id', $params['store_id']);
        }
        if (isset($params['province_id']) && $params['province_id']) {
            $query->where('province_id', $params['province_id']);
        }
        if (isset($params['city_id']) && $params['city_id']) {
            $query->where('city_id', $params['city_id']);
        }
        if (isset($params['district_id']) && $params['district_id']) {
            $query->where('district_id', $params['district_id']);
        }
        if (isset($params['street_id']) && $params['street_id']) {
            $query->where('street_id', $params['street_id']);
        }
        if (isset($params['store_name']) && $params['store_name']) {
            $query->where('store_name', 'like', '%' . $params['store_name'] . '%');
        }
        if (isset($params['category']) && $params['category']) {
            $query->where('category_id', $params['category']);
        }
        if (isset($params['member']) && $params['member']) {
            $query->whereHas('member', function ($member) use ($params) {
                $member->where('realname', 'like', '%' . $params['member'] . '%')
                    ->orWhere('id', 'like', '%' . $params['member'] . '%')
                    ->orWhere('mobile', 'like', '%' . $params['member'] . '%')
                    ->orWhere('nickname', 'like', '%' . $params['member'] . '%');
            });
        }
        if (isset($params['uid']) && $params['uid']) {
            $query->where('uid', $params['uid']);
        }
        if (isset($params['enter_status']) && in_array($params['enter_status'], [0, 1])) {
            $query->where('validity_status', $params['enter_status']);
        }
        return $query;
    }

    public function scopeVisible($query)
    {
        return $query->where('is_hide', 0);
    }

    public function scopeOperating($query)
    {
        return $query->where('validity_status', '!=', 1);
    }

    public function scopeByLocation($query, $province_id = null, $city_id = null, $district_id = null)
    {
        if ($province_id) {
            $query->where('province_id', $province_id);
        }
        if ($city_id) {
            $query->where('city_id', $city_id);
        }
        if ($district_id) {
            $query->where('district_id', $district_id);
        }
        return $query;
    }

    public function scopeByCategory($query, $category_id)
    {
        return $query->where('category_id', $category_id);
    }

    // 新增关系方法
    public function category()
    {
        return $this->belongsTo(StoreCategory::class, 'category_id');
    }

    public function storeOrders()
    {
        return $this->hasMany(StoreOrder::class, 'store_id');
    }

    public function storeSettings()
    {
        return $this->hasMany(StoreSetting::class, 'store_id');
    }

    public function storeGoods()
    {
        return $this->hasMany(StoreGoods::class, 'store_id');
    }

    public function goods()
    {
        return $this->hasMany(Goods::class, 'store_id');
    }

    public function getStoreSetting($key, $default = null)
    {
        $setting = $this->storeSettings()->where('key', $key)->first();
        return $setting ? $setting->value : $default;
    }

    // 验证规则
    public static function rules()
    {
        return [
            'store_name' => 'required|string|max:255',
            'uid' => 'required|integer',
            'category_id' => 'required|integer',
            'province_id' => 'required|integer',
            'city_id' => 'required|integer',
            'district_id' => 'required|integer',
        ];
    }

    public static function attributeNames()
    {
        return [
            'store_name' => '店铺名称',
            'uid' => '用户ID',
            'category_id' => '分类ID',
            'province_id' => '省份ID',
            'city_id' => '城市ID',
            'district_id' => '区县ID',
        ];
    }
}